package com.rainng.coursesystem.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rainng.coursesystem.dao.mapper.GeneralReportMapper;
import com.rainng.coursesystem.model.entity.GeneralReportEntity;
import com.rainng.coursesystem.model.excelvo.GeneralReportExcelVo;
import com.rainng.coursesystem.model.shitong.*;
import com.rainng.coursesystem.model.vo.response.ResultVO;
import org.springframework.stereotype.Service;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;

import javax.annotation.Resource;
import java.util.*;

import static com.rainng.coursesystem.model.constant.GeneralReportProjectMap.*;

@Service
public class GeneralReportService extends BaseService {

    @Resource
    private GeneralReportMapper generalReportMapper;

    public ResultVO getGeneralReportDetailsByFatherId(String id) {
        List<Map<String, Object>> r = generalReportMapper.getGeneralReportDetailsByFatherId(id);
        List<Map<String, Object>> res = new ArrayList<>();
        if (r.size() > 0) {
            // 382放到38之后
            for (Map<String, Object> m : r) {
                Integer prjNum = (int) m.get("prj_num");

                if ("382".equals(prjNum.toString())) {
                    break;
                }
                if (38 == prjNum) {
                    res.add(m);
                    res.add(r.get(r.size() - 1));
                } else {
                    res.add(m);
                }
            }
        }
        return result(res);
    }

    public ResultVO getGeneralReportByApplyNum(String applyNum) {
        List<GeneralReportEntity> ra = generalReportMapper.getOneGeneralReportByApplyNum(applyNum);
        if (ra.size() == 0) {
            return failedResult("先新增总报告");
        }
        return result(ra.get(0));
    }


    public ResultVO getGeneralReportDetailsByApplyNum(String applyNum) {
        List<Integer> ra = generalReportMapper.getGeneralReportIdByApplyNum(applyNum);
        if (ra.size() == 0) {
            return failedResult("先新增总报告");
        }
        List<Map<String, Object>> r = new ArrayList<>();
        if (ra.size() > 0) {
            String id = ra.get(0).toString();
            r = generalReportMapper.getGeneralReportDetailsByFatherId(id);
            List<Map<String, Object>> res = new ArrayList<>();
            if (r.size() > 0) {
                // 382放到38之后
                for (Map<String, Object> m : r) {
                    Integer prjNum = (int) m.get("prj_num");

                    if ("382".equals(prjNum.toString())) {
                        break;
                    }
                    if (38 == prjNum) {
                        res.add(m);
                        Map<String,Object> mtemp = r.get(r.size() - 1);
                        String p = mtemp.get("prj_num").toString();
                        if ("382".equals(p)){
                            res.add(mtemp);
                        }

                    } else {
                        res.add(m);
                    }
                }
            }
            return result(res);
        }
        return result(r);
    }

    // 修改 静态map来源于数据库
    public ResultVO saveGeneralReportFromTask(GeneralReportSaveVo vo) {
        if (StrUtil.isEmpty(vo.getApplyNum()) || StrUtil.isEmpty(vo.getNumId())) {
            return failedResult("申请编号和n_id不能为空");
        }
        List<Map<String, Object>> prj_list = generalReportMapper.getGeneralReportPrjNum(vo.getVeType());
        Map <String,String> prj = new HashMap<>();
        for(Map<String, Object> entry : prj_list){
            prj.put( entry.get("prj_num").toString(), (String) entry.get("prj_name"));
        }

        List<Map<String, Object>> according_list = generalReportMapper.getGeneralReportAccording(vo.getVeType());
        Map <String,String> according = new HashMap<>();
        for(Map<String, Object> entry : according_list){
            according.put(entry.get("prj_num").toString(), (String) entry.get("according"));
        }

        List<Map<String, Object>> shiyongfanwei_list = generalReportMapper.getGeneralReportUserange(vo.getVeType());
        Map <String,String> shiyongfanwei = new HashMap<>();
        for(Map<String, Object> entry : shiyongfanwei_list){
            shiyongfanwei.put(entry.get("prj_num").toString(), (String) entry.get("use_range"));
        }

        Map <String,String> h_valid = new HashMap<>();
        //不存在则新增,存在则更新
        List<Integer> exist = generalReportMapper.getGeneralReportIdByApplyNum(vo.getApplyNum());
        if (exist.size() > 0) {
            GeneralReportUpdatePo po = new GeneralReportUpdatePo();
            po.setVeModel(vo.getVeModel());
            po.setApplyNum(vo.getApplyNum());
            po.setTaskName(vo.getTaskName());
            po.setCusName(vo.getCusName());
            po.setTaskCode(vo.getTaskCode());
            int f = generalReportMapper.updateGeneralReportByTask(po);
            //
            Integer fid = exist.get(0);
            List<String> prjs = generalReportMapper.selectPrjNumsByFatherId(fid.toString());
            //处理总报告初始化
            if ("载货汽车".equals(vo.getVeType())||"牵引车辆".equals(vo.getVeType())||"半挂车".equals(vo.getVeType())) {

                for (Map.Entry<String, String> entry : prj.entrySet()) {
                    String k = entry.getKey();
                    if (prjs.contains(k)){
                        continue;
                    }
                    String v = entry.getValue();
                    GeneralReportDetailPo dpo = new GeneralReportDetailPo();
                    dpo.setAccording(according.get(entry.getKey()));
                    dpo.setFid(fid);
                    dpo.setVeType(vo.getVeType());
                    dpo.setPrjnum(k);
                    dpo.setPrjname(v);
                    dpo.setUseRange(shiyongfanwei.get(entry.getKey()));
                    dpo.setValid(1);
                    int j = generalReportMapper.saveGeneralReportDetail(dpo);
                }
            }
            return result(exist.get(0), "修改成功");
        }

        GeneralReportEntity entity = new GeneralReportEntity();
        BeanUtil.copyProperties(vo, entity);
        entity.setCreateTime(new Date());
        entity.setVeModel(vo.getVeModel());
        entity.setApplyNum(vo.getApplyNum());
        entity.setTaskName(vo.getTaskName());
        entity.setTaskCode(vo.getTaskCode());
        entity.setCusName(vo.getCusName());
        int i = generalReportMapper.saveGeneralReportByTask(entity);
        //System.out.println(i);
        if ("载货汽车".equals(vo.getVeType())||"牵引车辆".equals(vo.getVeType())||"半挂车".equals(vo.getVeType())) {
            for (Map.Entry<String, String> entry : prj.entrySet()) {
                String k = entry.getKey();
                String v = entry.getValue();
                GeneralReportDetailPo po = new GeneralReportDetailPo();
                po.setAccording(according.get(entry.getKey()));
                po.setFid(entity.getId());
                po.setVeType(entity.getVeType());
                po.setPrjnum(k);
                po.setPrjname(v);
                po.setUseRange(shiyongfanwei.get(entry.getKey()));
                po.setValid(1);
                int j = generalReportMapper.saveGeneralReportDetail(po);
            }
        }
        int f = generalReportMapper.updateTaskWithReportByApplyNum(vo.getApplyNum());
        return result(entity.getId(), "新增成功");
    }


    public ResultVO deleteGeneralReportById(String id) {
        int i = generalReportMapper.deleteGeneralReportById(id);
        // 级联删除
        int j = generalReportMapper.deleteGeneralReportDetailByFatherId(id);
        return result(i);
    }

    public ResultVO deleteGeneralReportByApplyNum(String applyNum) {
        List<Integer> r = generalReportMapper.getGeneralReportIdByApplyNum(applyNum);
        List<Map<String, Object>> res = new ArrayList<>();
        if (r.size() > 0) {
            String id = r.get(0).toString();
            int i = generalReportMapper.deleteGeneralReportById(id);
            // 级联删除
            int j = generalReportMapper.deleteGeneralReportDetailByFatherId(id);
        }
        return result(r.size());
    }

    public ResultVO countGeneralReport(GeneralReportVo cvo) {
        int i = generalReportMapper.countGeneralReport(cvo);
        return result(i);
    }

    public ResultVO selectGeneralReport(GeneralReportVo cvo) {
        Page<GeneralReportEntity> pageParam = new Page<>(cvo.getPageNum(), cvo.getPageSize());
        IPage<GeneralReportEntity> entities = generalReportMapper.queryGeneralReport(cvo, pageParam);
        List<GeneralReportEntity> res = entities.getRecords();
        return result(res);
    }

    public ResultVO updateGeneralReportDetailById(GeneralReportDetailUpdatePo po) {
        int i = generalReportMapper.updateGeneralReportDetailsById(po);
        return result(i);
    }

    public ResultVO updateMultiGeneralReportDetailById(List<GeneralReportDetailUpdatePo> pos) {

        for (GeneralReportDetailUpdatePo po : pos) {
            int i = generalReportMapper.updateGeneralReportDetailsById(po);
        }
        return result("更新成功");
    }

    public ResultVO updateGeneralReportById(GeneralReportUpdatePo po) {
        int i = generalReportMapper.updateGeneralReportById(po);
        return result("更新成功");
    }

    public void saveGeneralReportByImport(List<GeneralReportExcelVo> lists, String applynum,Map<String,Object> m) {
        // 判断总报告是否存在
        List<GeneralReportEntity> grelists = generalReportMapper.getOneGeneralReportByApplyNum(applynum);

        String fid = grelists.get(0).getId().toString();
        String veType = grelists.get(0).getVeType();
        //总报告已存在
//        GeneralReportSaveVo vo = new GeneralReportSaveVo();
//        //导入总报告
//        vo.setApplyNum(applynum);
//        if (m.get("num_id") != null)
//            vo.setNumId(m.get("num_id").toString());
//        if (m.get("ve_type") != null)
//            vo.setVeType(m.get("ve_type").toString());
//        if (m.get("ve_model") != null)
//            vo.setVeModel(m.get("ve_model").toString());
//        if (m.get("task_name") != null)
//            vo.setTaskName(m.get("task_name").toString());
//        ResultVO r = saveGeneralReportFromTask(vo);
//        String fid = r.getData().toString();
        //更新接口
//      List<String> prj_temp = new ArrayList<>();
        //来源静态map 然后改成来源于数据库
//        Set prjkeys = GENERAL_REPORT_PRJ.keySet();
        List<Map<String,Object>> objlist = generalReportMapper.selectPrjMapByVeType(veType);
        Map<String, String> geneal_report_prj = new HashMap<>();
        geneal_report_prj.put("型号：", "型号：");
        //第二行
        geneal_report_prj.put("项目代号", "项目代号");
        for(Map<String,Object> ma : objlist){
            geneal_report_prj.put(ma.get("prj_code").toString(),ma.get("prj_num").toString());
        }
        Set prjkeys = geneal_report_prj.keySet();

        //List<GeneralReportDetailUpdatePo> pos = new ArrayList<>();

        //list转为更新类
        for (GeneralReportExcelVo po : lists) {
            if ("型号：".equals(po.getProjectId())) {
//                System.out.println("第一行可以处理可以不处理");
                continue;
            }
            if ("项目代号".equals(po.getProjectId())) {
//                System.out.println("第二行不用处理");
                continue;
            }
            String pid = po.getProjectId();
            //无须处理项
            if (!prjkeys.contains(pid)) {
                continue;
            }
            GeneralReportDetailUpdatePo grdup = new GeneralReportDetailUpdatePo();
            BeanUtil.copyProperties(po, grdup);//第一个参数向第二个赋值
            grdup.setPrjNum(geneal_report_prj.get(pid));

//            System.out.println(grdup.getCheckType());
            if ("○".equals(grdup.getCheckType())) {
                grdup.setCheckType("1");
            }
            if ("△".equals(grdup.getCheckType())) {
                grdup.setCheckType("2");
            }
            if ("○△".equals(grdup.getCheckType())) {
                grdup.setCheckType("3");
            }
            if (grdup.getRemark() == null) {
                grdup.setRemark("");
            }
            if (grdup.getShiceNum() == null) {
                grdup.setShiceNum("");
            }
            if (grdup.getShitongModel() == null) {
                grdup.setShitongModel("");
            }
            if(grdup.getReportName()==null){
                grdup.setReportName("");
            }
            int j = generalReportMapper.updateGeneralReportDetailsByFatherIdAndPrjNum(grdup, fid, geneal_report_prj.get(pid));
            //System.out.println("更新完成");

            //String prjNum = po.getPrjNum();
//            if(!prjkeys.contains("prjNum")){
//                return;
//            }
            //int i = generalReportMapper.updateGeneralReportDetailsByFatherIdAndPrjNum(null,fid,null);
        }

        return;
    }


}
